# encoding: utf-8
import os

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.ext.db import djangoforms
import taggable


class Post(db.Model,taggable.Taggable):
    """A Post category"""
    title = db.StringProperty(required=True)
    content = db.TextProperty(required=True)
    excerpt = db.StringProperty()
    permalink = db.StringProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)
    published = db.DateTimeProperty()
    creator = db.UserProperty(required=True)
    categories_keys = db.ListProperty(db.Key)
    draft = db.BooleanProperty(required=True, default=True)
    post_type = db.StringProperty(required=True, choices=set(["page", "post"]), default="post")
    comments_enabled = db.BooleanProperty(required=True, default=True)
    _categories = None
    
    def __init__(self, parent=None, key_name=None, app=None, **entity_values):
        db.Model.__init__(self, parent, key_name, app, **entity_values)
        taggable.Taggable.__init__(self)

    @property
    def categories(self):
        """The list of categories of a post.
        
        The value is expensive to compute, so it is cached.
        """
        if self._categories is None:
            self._categories = (db.get(key) for key in self.categories_keys)
        return self._categories
        
    _num_comments = None

    @property
    def num_comments(self):
        """The number of comments for this post.

        The value is expensive to compute, so it is cached.
        """
        if self._num_comments is None:
            self._num_comments = Comment.gql('WHERE post=:1', self).count()
        return self._num_comments
    
    _comments = None

    @property
    def comments(self):
        """The number of comments for this post.

        The value is expensive to compute, so it is cached.
        """
        if self._comments is None:
            self._comments = Comment.gql('WHERE post=:1', self)
        return self._comments
    
#    @property
#    def yearmonthdate(self):
#        """The number of comments for this post.
#
#        The value is expensive to compute, so it is cached.
#        """
#        md=self.modified.strftime('%Y-%m-%d')
#        if self.yearmonthdate is None and md !=self.yearmonthdate:
#            self.yearmonthdate =self.modified.strftime('%Y-%m-%d')
#            self.put()
#        return self.yearmonthdate
    
class Category(db.Model):
    """"""
    category_name = db.StringProperty(required=True)
    category_url = db.StringProperty(required=True)

class Comment(db.Model):
    """A Comment for a specific post. """

    post = db.ReferenceProperty(Post)  # == parent
    ip = db.StringProperty()
    date = db.DateTimeProperty(auto_now=True)
    author = db.StringProperty(required=True)
    email = db.EmailProperty(required=True)
    link = db.LinkProperty()
    text = db.TextProperty(required=True)
    type = db.StringProperty(required=True, choices=set(["comment", "trackback"]), default="comment")
    
class CommentForm(djangoforms.ModelForm):
    class Meta:
        model = Comment
        exclude = ['ip','post','type']

class Link(db.Model):
    name = db.StringProperty(required=True)
    link = db.LinkProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)
    

class LinkForm(djangoforms.ModelForm):
    class Meta:
        model = Link
        
  
class CachedPage(db.Model):
    """docstring for CachedPage"""
    html = db.BlobProperty()
    type = db.StringProperty()
    content_type = db.StringProperty(default='text/html')
    created = db.DateTimeProperty(auto_now_add=True)

class SidebarWidget(db.Model):
    name = db.StringProperty(required=True)
    title = db.StringProperty()
    text = db.TextProperty(required=True)
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)    

class SidebarWidgetForm(djangoforms.ModelForm):
    class Meta:
        model = SidebarWidget

class Option(db.Model):
    label = db.StringProperty(required=True)
    name = db.StringProperty(required=True)
    value = db.StringProperty()
    #Option._properties["theme"].choices
    option_type = db.StringProperty(required=True, choices=set(['int', 'str', 'boolean', 'list','select']), default='int')
    space = db.StringProperty(required=True, default = 'global')
    created = db.DateTimeProperty(auto_now_add=True)
    modified = db.DateTimeProperty(auto_now=True)    
    selected_value = db.StringProperty()
    @property
    def html(self):
        if self.option_type == 'boolean':
            str ='<input type="checkbox" name="%s" value="True" id="%s" ' % (self.name, self.name) 
            if self.value == 'True':
                str = str + 'checked="checked"'
            str = str + ' >'
            return str
        elif self.option_type =='list':
            list_seperator=','
            value =''
            if self.value:
                value =self.value
                
#                for item in value:
#                    type(item)
            return '<input type="text" name="%s" value="%s" id="%s" />' % (self.name, unicode(list_seperator.join(eval(value))), self.name)
        elif self.option_type =='select':
#            <select id="id_theme" name="theme">
#<option value=".svn">.svn</option>
#<option value="compressed">compressed</option>
#<option selected="selected" value="default">default</option>
#<option value="resplendissant">resplendissant</option>
#<option value="thermal">thermal</option>
#<option value="unsightly">unsightly</option>
#</select>
            str=''
            str=str+'''<select name="%s" id="%s" >''' % (self.name,self.name)
            list = eval(self.selected_value)
            for li in list:
                if li!=self.value:
                    str=str+'''<option value="'''+li+'''">'''+li+'''</option>'''
                else:
                    str=str+'''<option value="'''+li+'''" selected="selected">'''+li+'''</option>'''
            str=str+'''</select>'''
            return str
        else:
            value = ''
            if self.value:
                value = self.value
            return '<input type="text" name="%s" value="%s" id="%s" />' % (self.name, value, self.name)

class UploadFile(db.Model):
    data = db.BlobProperty()
    orig_name = db.StringProperty()
    ext = db.StringProperty()
    date = db.DateTimeProperty(auto_now_add=True)

    def name(self):
        if self.ext:
            return str(self.key()) + '.' + self.ext
        else:
            return str(self.key())

class Archive(db.Model):
#    blog = db.ReferenceProperty(Post)
    yearmonth = db.StringProperty(multiline=False)
    """08-08-19"""
    entrycount = db.IntegerProperty(default=0)

class Lrc(db.Model):
#    blog = db.ReferenceProperty(Post)
    albumName = db.StringProperty(multiline=False)
    albumUrl = db.StringProperty(multiline=False)
    artist = db.StringProperty(multiline=False)
    songName = db.StringProperty(multiline=False)
    songUrl = db.StringProperty(multiline=False)
    sourcesite = db.StringProperty(multiline=False)
    content = db.TextProperty(required=True)
    date = db.DateTimeProperty(auto_now_add=True)
    
class Code(db.Model):
    data = db.BlobProperty()
    orig_name = db.StringProperty()
    user = db.UserProperty(required=True)
    active = db.BooleanProperty(default=False)
    order = db.IntegerProperty(default=0)
    date = db.DateTimeProperty(auto_now_add=True)
    
class ResquestCounter(db.Model):
    ip = db.StringProperty()
    userAgent = db.StringProperty()
    referer = db.StringProperty()
    url = db.StringProperty()
    requestTime = db.DateTimeProperty(auto_now_add=True)

class Feed(db.Model):
    link_autor=db.StringProperty()
    link=db.StringProperty()
    link_alt=db.StringProperty()
    order=db.IntegerProperty(default=1)